using System;
using System.Reflection;
using UnityEngine;

namespace NodeCanvas.Conditions
{
	[Category("✫ Script Control")]
	[Description("Will subscribe to an event of EventHandler type or custom handler with zero parameters and return type of void")]
	[AgentType(typeof(Transform))]
	public class CheckCSharpEvent : ConditionTask
	{
		[RequiredField]
		public Component script;

		[RequiredField]
		public string eventName;

		protected override string info
		{
			get
			{
				return "'" + eventName + "' Raised";
			}
		}

		protected override string OnInit()
		{
			EventInfo eventInfo = script.GetType().NCGetEvent(eventName);
			if (eventInfo == null)
			{
				return "Event was not found";
			}
			Delegate handler;
			if (eventInfo.EventHandlerType == typeof(System.EventHandler))
			{
				MethodInfo methodInfo = GetType().NCGetMethod("DefaultRaised");
				handler = NCReflection.NCCreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
			}
			else
			{
				MethodInfo methodInfo = GetType().NCGetMethod("Raised");
				handler = NCReflection.NCCreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
			}
			eventInfo.AddEventHandler(script, handler);
			return null;
		}

		public void DefaultRaised(object sender, EventArgs e)
		{
			Raised();
		}

		public void Raised()
		{
			YieldReturn(true);
		}

		protected override bool OnCheck()
		{
			return false;
		}
	}
}
